package com.qiwx.pigeon.activity.common;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;

import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DateTimeUtils;
import com.qiwx.pigeon.base.Constant;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 选择时间界面
 *
 * @author 作者 彭坤
 * @version 创建时间：2016-5-4
 */
@SuppressLint("NewApi")
public class SelectDateActivity extends FragmentActivity {

    int win_width;
    int win_height;
    @BindView(R.id.time_title)
    TextView timeTitle;
    @BindView(R.id.yearNumberPicker)
    MyNumberPicker yearNumberPicker;
    @BindView(R.id.monthNumberPicker)
    MyNumberPicker monthNumberPicker;
    @BindView(R.id.dial_layout)
    LinearLayout dialLayout;
    @BindView(R.id.dayNumberPicker)
    MyNumberPicker dayNumberPicker;
    @BindView(R.id.txtdayNumberPicker)
    TextView txtdayNumberPicker;
    public static final int REQUEST_CODE_START = 1000;
    public static final int REQUEST_CODE_END = 1001;

    private int currYear = DateTimeUtils.getCurrent(DateTimeUtils.TimeType.YEAR);//默认当前年
    private int currMonth = DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH);//默认当前月
    private int currDay = DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY);//默认当前日

    private  int maxYear = DateTimeUtils.getCurrent(DateTimeUtils.TimeType.YEAR);//默认当前年
    private int  minYear;
    private int minMonth = 1;

    private int minDay=1;
    private int term; //新增期限值，从当前日期往后推多少年
    private String ymd;//反显的值

    private Unbinder unbinder;
    private boolean isShowDay=true;//是否显示到天 默认显示

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // 隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setFinishOnTouchOutside(true);
        setContentView(R.layout.act_day_sheettime);
        unbinder = ButterKnife.bind(this);
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
        WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
        Point size = new Point();
        d.getSize(size);
        win_width = size.x;
        win_height = size.y;
        p.gravity = Gravity.BOTTOM;
        p.height = (int) (win_height * 0.5); // 高度设置为屏幕的0.6
        p.width = win_width * 1; // 宽度设置为屏幕的1
        p.alpha = 1.0f;// 设置透明度
        this.getWindow().setAttributes(p);


        Intent intent = getIntent();
        maxYear = intent.getIntExtra("maxYear",currYear);
        minYear = getIntent().getIntExtra("Minyear", 1990);
        minMonth = getIntent().getIntExtra("MinMonth", 1);
        minDay=getIntent().getIntExtra("MinDay",1);
        term=getIntent().getIntExtra("term",0);
        ymd=getIntent().getStringExtra("ymd");
        isShowDay=getIntent().getBooleanExtra("isShowDay",true);
        //maxMonth = getIntent().getIntExtra("maxMonth", 1);
        String title = intent.getStringExtra(Constant.KEY_TITLE);
        if (!TextUtils.isEmpty(title)) {
            timeTitle.setText(title);
        }
        if(!isShowDay){
            dayNumberPicker.setVisibility(View.GONE);
            txtdayNumberPicker.setVisibility(View.GONE);
        }

        yearNumberPicker.setMaxValue(maxYear);
        yearNumberPicker.setMinValue(minYear);
        yearNumberPicker.setValue(currYear);

        if (maxYear<currYear){
            currYear = maxYear;
            yearNumberPicker.setValue(currYear);
            monthNumberPicker.setMaxValue(12);
            monthNumberPicker.setMinValue(1);
            monthNumberPicker.setValue(1);
        }else {
            monthNumberPicker.setMaxValue(currMonth);
            monthNumberPicker.setMinValue(minMonth);
            monthNumberPicker.setValue(currMonth);
        }


        dayNumberPicker.setMaxValue(currDay);
        dayNumberPicker.setMinValue(1);
        dayNumberPicker.setValue(currDay);


        if (term!=0 && term>0){

            minYear = currYear;
            maxYear = currYear+term;

            minMonth = currMonth;

            yearNumberPicker.setMaxValue(currYear+term);
            yearNumberPicker.setMinValue(currYear);
            yearNumberPicker.setValue(currYear+1);

            monthNumberPicker.setMaxValue(currMonth);
            monthNumberPicker.setMinValue(1);
            monthNumberPicker.setValue(currMonth);

            dayNumberPicker.setMinValue(1);
            dayNumberPicker.setValue(currDay-1);

            if (is31(currMonth)) {
                dayNumberPicker.setMaxValue(31);
            } else {
                if (currMonth == 2) {
                    if (isRunNian(String.valueOf(currYear))) {
                        dayNumberPicker.setMaxValue(29);
                    } else {
                        dayNumberPicker.setMaxValue(28);
                    }

                } else {
                    dayNumberPicker.setMaxValue(30);
                }
            }

        }



        yearNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        monthNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        dayNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        yearNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int year = picker.getValue();
                currYear = year;
                updateMonth();
            }
        });
        monthNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int month = picker.getValue();
                currMonth = month;
                updateMonth();

            }
        });
        dayNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int day = picker.getValue();
                currDay = day;
            }
        });

        updateMonth();


//        if (!TextUtils.isEmpty(ymd)){
//            String[] pwd = ymd.split("-");
//            if (pwd.length==2){
//                yearNumberPicker.setValue(Integer.valueOf(pwd[0]));
//                monthNumberPicker.setValue(Integer.valueOf(pwd[1]));
//            }else if (pwd.length==3){
//                yearNumberPicker.setValue(Integer.valueOf(pwd[0]));
//                monthNumberPicker.setValue(Integer.valueOf(pwd[1]));
//                dayNumberPicker.setValue(Integer.valueOf(pwd[2]));
//            }
//        }

    }


    public void updateMonth() {
        //当前年
        if (term!=0 && term >0){

            int year = yearNumberPicker.getValue();

            if (year == minYear){
                monthNumberPicker.setMaxValue(12);
                monthNumberPicker.setMinValue(minMonth);
            }else if(year == maxYear){
                monthNumberPicker.setMaxValue(minMonth);
                monthNumberPicker.setMinValue(1);
            }else {
                monthNumberPicker.setMaxValue(12);
                monthNumberPicker.setMinValue(1);
            }
        }else {

            if (currYear == DateTimeUtils.getCurrent(DateTimeUtils.TimeType.YEAR)) { //如果选择当前年，则重新设置月和日的范围，不等大于当前月，不能大于当前日
                monthNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH));
                monthNumberPicker.setMinValue(1);
                if (currMonth == DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH)) {
                    dayNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY));
                } else {
                    dayNumberPicker.setMaxValue(31);
                }

            } else if (yearNumberPicker.getValue() == minYear) {
                monthNumberPicker.setMaxValue(12);
                monthNumberPicker.setMinValue(minMonth);
            } else {
                monthNumberPicker.setMaxValue(12);
//            monthNumberPicker.setValue(currMonth);
                monthNumberPicker.setMinValue(1);
            }
        }


        updateDay();

    }

    public void updateDay() {
        int year = yearNumberPicker.getValue();
        int month = monthNumberPicker.getValue();
        if (is31(month)) {
            dayNumberPicker.setMaxValue(31);
        } else {
            if (month == 2) {
                if (isRunNian(String.valueOf(year))) {
                    dayNumberPicker.setMaxValue(29);
                } else {
                    dayNumberPicker.setMaxValue(28);
                }

            } else {
                dayNumberPicker.setMaxValue(30);
            }
        }

        if (term != 0 && term >0){

            if (year == minYear && month == minMonth){
                dayNumberPicker.setMinValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY));
            }else if(year == maxYear && month == minMonth){
                dayNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY));
                dayNumberPicker.setMinValue(1);
            }else {
                dayNumberPicker.setMinValue(1);
            }

        }else {

            if (year == DateTimeUtils.getCurrent(DateTimeUtils.TimeType.YEAR)) {//如果选择当前年，则重新设置月和日的范围，不等大于当前月，不能大于当前日

                monthNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH));
                if (currMonth == DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH)) {
                    dayNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY));
                }
            }else if(year==minYear&&month==minMonth){//如果选择当前最小年和月日期小于最小日期
                dayNumberPicker.setMinValue(minDay);
            }
        }


    }

    /**
     * 根据月份判断是否是31天
     *
     * @param month
     * @return
     */
    public boolean is31(int month) {
        Pattern pattern = Pattern.compile("([13578]|1[02])");
        Matcher matcher = pattern.matcher(month + "");
        return matcher.matches();
    }

    /**
     * 判断是否是闰年
     *
     * @param year
     * @return
     */
    public boolean isRunNian(String year) {
        Pattern pattern = Pattern.compile("(([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))");
        Matcher matcher = pattern.matcher(year);
        return matcher.matches();
    }

    public void cancel(View view) {
        finish();
    }

    public void time_done(View view) {
        back_data();
        finish();
    }


    public void back_data() {
        Intent in = new Intent();
        int year = yearNumberPicker.getValue();
        int month = monthNumberPicker.getValue();
        int day = dayNumberPicker.getValue();
        StringBuilder sb = new StringBuilder();
        sb.append(year).append("-");
        if (month < 10) {
            sb.append("0" + month);
        } else {
            sb.append(month);
        }
        sb.append("-");
        if (day < 10) {
            sb.append("0" + day);
        } else {
            sb.append(day);
        }
        in.putExtra("car_Time_MSG", sb.toString());
        setResult(RESULT_OK, in);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }



}
